@()(implicit session: Session)
@english.home.main("Muscle - Tools"){

    <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("phylotree.js-master/phylotree.css")">
    <script src="@routes.Assets.versioned("phylotree.js-master/d3.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("phylotree.js-master/phylotree.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("phylotree.js-master/underscore.min.js")" type="text/javascript"></script>
    <script type="text/javascript" src="@routes.Assets.versioned("phylotree.js-master/vis.min.js")"></script>

    <style>

            .fa-rotate-135 {
                -webkit-transform: rotate(135deg);
                -moz-transform: rotate(135deg);
                -ms-transform: rotate(135deg);
                -o-transform: rotate(135deg);
                transform: rotate(135deg);
            }

            .fa-rotate-45 {
                -webkit-transform: rotate(45deg);
                -moz-transform: rotate(45deg);
                -ms-transform: rotate(45deg);
                -o-transform: rotate(45deg);
                transform: rotate(45deg);
            }

            .myGroup {
                margin-top: 15px;
                margin-left: 15px;
            }

    </style>

    <div id="content">
        <h1 class="title">Tools - Muscle</h1>
        <div class="line"></div>
        <div class="tab_container" style="margin-bottom: 30px;padding-top: 30px">

        <form class="registration-form form-horizontal" id="form" accept-charset="UTF-8">

            <div class="form-group">
                <label class="control-label col-sm-3">Type of query:</label>
                <div class="col-sm-4">
                    <select class="form-control" onchange="change(this)" name="method">
                        <option selected value="text">Text</option>
                        <option value="file">File</option>
                    </select>
                </div>
            </div>

            <div class="form-group"  id="QueryContent">
                <label class="control-label col-sm-3">Enter FASTA sequences:</label>
                <div class="col-sm-8">
                    <textarea class="form-control monospace" name="queryText" id="queryText" rows="7"
                    ></textarea>
                    <span class="help-block">e.g.,&nbsp;<a href="#"><em id="egQuery">
                        example</em></a></span>
                </div>
            </div>

            <div class="form-group" id="QueryFile" style="display: none;">
                <label class="control-label col-sm-3">Or, upload file:</label>
                <div class="col-sm-8">
                    <input id="input-1" type="file" class="file control-label" name="file" data-show-preview="false"
                    data-show-upload="false">
                    <span class="help-block"><a onclick="showExampleFile()"><em>
                        Example file</em></a></span>
                </div>
            </div>

            <div class="form-group">
                <label class="control-label col-sm-3">Output Tree:</label>
                <div class="col-sm-3">
                    <select id="tree" name="tree" class="form-control">
                        <option selected="selected" value="none">none</option>
                        <option value="tree1">From first iteration</option>
                        <option value="tree2">From second iteration</option> </select>
                </div>

            </div>


            <div class="form-group">
                <div class="actions col-sm-offset-3 col-sm-2">
                    <a href="#" class="button blue" onclick="mySearch()">Run</a>
                </div>
            </div>


        </form>
        </div>
        <hr>
        <div id="result" style="display: none;">
            <h4>Result:</h4>
            <h5>Fasta result:
                &nbsp;<button class="btn btn-primary" onclick="downloadFasta()"><i class="fa fa-download"></i>&nbsp;Download</button>
            </h5>
            <pre id="out" style="background-color: white"></pre>
            <div id="treeContent">
                <h5>Tree result:
                    &nbsp;<button class="btn btn-primary" onclick="downloadTree()"><i class="fa fa-download"></i>&nbsp;Download</button>
                </h5>
                <pre id="treeOut" style="background-color: white"></pre>
                <h5>Tree plot:
                    <form action="/mollusk/tools/downloadTree" method="post" onsubmit="mySubmit()" style="display: inline">
                        <input type="hidden" name="svgHtml" id="svgHtml">
                            &nbsp;<button class="btn btn-primary" type="submit"><i class="fa fa-download"></i>&nbsp;Download</button>
                    </form>
                </h5>
                <div style="border: 1px solid #ccc;">
                    <div>
                        <div class="btn-group myGroup">
                            <button type="button" class="btn btn-default btn-sm" data-direction="vertical" data-amount="1" title="Expand vertical spacing">
                                <i class="fa fa-arrows-v"></i>
                            </button>
                            <button type="button" class="btn btn-default btn-sm" data-direction="vertical" data-amount="-1" title="Compress vertical spacing">
                                <i class="fa  fa-compress fa-rotate-135"></i>
                            </button>
                            <button id="leftRight" type="button" class="btn btn-default btn-sm" data-direction="horizontal" data-amount="1" title="Expand horizonal spacing">
                                <i class="fa fa-arrows-h"></i>
                            </button>
                            <button type="button" class="btn btn-default btn-sm" data-direction="horizontal" data-amount="-1" title="Compress horizonal spacing">
                                <i class="fa  fa-compress fa-rotate-45"></i>
                            </button>
                            <button type="button" class="btn btn-default btn-sm" id="sort_ascending" title="Sort deepest clades to the bototm">
                                <i class="fa fa-sort-amount-asc"></i>
                            </button>
                            <button type="button" class="btn btn-default btn-sm" id="sort_descending" title="Sort deepsest clades to the top">
                                <i class="fa fa-sort-amount-desc"></i>
                            </button>
                            <button type="button" class="btn btn-default btn-sm" id="sort_original" title="Restore original order">
                                <i class="fa fa-sort"></i>
                            </button>
                        </div>
                        <div class="btn-group myGroup" data-toggle="buttons">
                            <label class="btn btn-default btn-sm active" id="linear">
                                <input name="options" class="phylotree-layout-mode" data-mode="linear" autocomplete="off" checked="" title="Layout left-to-right" type="radio">
                                Linear
                            </label>
                            <label class="btn btn-default  btn-sm">
                                <input name="options" class="phylotree-layout-mode" data-mode="radial" autocomplete="off" title="Layout radially" type="radio">
                                Radial
                            </label>
                        </div>
                        <div class="btn-group myGroup" data-toggle="buttons">
                            <label class="btn btn-default active btn-sm" id="defaultAlign">
                                <input class="phylotree-align-toggler" data-align="left" name="options-align" autocomplete="off" checked="" title="Align tips labels to branches" type="radio">
                                <i class="fa fa-align-left"></i>
                            </label>
                            <label class="btn btn-default btn-sm">
                                <input class="phylotree-align-toggler" data-align="right" name="options-align" autocomplete="off" title="Align tips labels to the edge of the plot" type="radio">
                                <i class="fa fa-align-right"></i>

                            </label>
                        </div>
                    </div>

                    <svg id="tree_display" xmlns='http://www.w3.org/2000/svg' xmlns:xlink="http://www.w3.org/1999/xlink"></svg>
                </div>
            </div>
        </div>

    </div>
        <!-- End Content -->
    <div class="clear"></div>

    <script>
            var tree;
            var eg;

            function downloadFasta() {
                var fileName = "fasta.txt";
                var content = $("#out").text();
                var blob = new Blob([content], {
                    type: "text/plain;charset=utf-8"
                });
                saveAs(blob, fileName)
            }

            function change(element) {
                var value = $(element).find(">option:selected").val();
                if (value == "text") {
                    $("#QueryContent").show();
                    $("#QueryFile").hide()
                } else {
                    $("#QueryContent").hide();
                    $("#QueryFile").show()
                }
            }

            function mySubmit() {
                var html = $("svg:first").prop("outerHTML");
                $("#svgHtml").val(html);
                return true
            }

            function showExampleFile() {
                var w = window.open();
                $(w.document.body).html("<pre>"+eg+"</pre>")
            }

            function downloadTree() {
                var fileName = "newick.txt";
                var content = $("#treeOut").text();
                var blob = new Blob([content], {
                    type: "text/plain;charset=utf-8"
                });
                saveAs(blob, fileName)
            }

            $(function () {
                $("#sort_original").on("click", function (e) {
                    tree.resort_children(function (a, b) {
                        return a["original_child_order"] - b["original_child_order"];
                    });
                });

                $("#sort_ascending").on("click", function (e) {
                    sort_nodes(true);
                });

                $("#sort_descending").on("click", function (e) {
                    sort_nodes(false);
                });

                $(".phylotree-layout-mode").on("change", function (e) {
                    if ($(this).is(':checked')) {
                        if (tree.radial() != ($(this).data("mode") == "radial")) {
                            tree.radial(!tree.radial()).placenodes().update();
                        }
                    }
                });

                $("[data-direction]").on("click", function (e) {
                    var which_function = $(this).data("direction") === 'vertical' ? tree.spacing_x : tree.spacing_y;
                    which_function(which_function() + (+$(this).data("amount"))).update();
                });

                $(".phylotree-align-toggler").on("change", function (e) {
                    if ($(this).is(':checked')) {
                        if (tree.align_tips($(this).data("align") === "right")) {
                            tree.placenodes().update();
                        }
                    }
                });

                formValidation();

                eg = ">CAC24581.1    sequence:AJ294725:11107:11280:+  ORF57;   complete gene\n" +
                        "MFYFRDFNMVVKQEEGSTLFFNMYKYILKKLKRFSLYIFNIIKYVIIFVV\n" +
                        "YLINKSF\n" +
                        ">CAC24586.1    sequence:AJ294725:14857:15720:+  ORF287;   complete gene\n" +
                        "MFFICFNKKSNVVGLQISKCSGEFCIYREPKDKTYWNNFYYMSFYVNNKK\n" +
                        "VGVNCNITDIEYSLLDIFLHGPFQVNLSEYLNVCDCVNKRFLKYERMLKE\n" +
                        "KVVNGININFSLCENKNSLVFLDNYNLQEYLGPNNVLYVFVNSVLMDKKY\n" +
                        "FSREIRNKDFWNEWRCTKMPLYVNSKRVGKFYYYSEYVLHSLPGEEPNVL\n" +
                        "EYFVLDLFLFGPVEIEVSEYEKRTKQREYNTSLYLYLYKMDLISGVNIIF\n" +
                        "DEKTTDYSKILQTQFQTYHNLDDDRILNVCVITRMRL\n" +
                        ">CAC24594.1    sequence:AJ294725:20661:20978:+  ORF105;   complete gene\n" +
                        "MFFDLYEIILYILFFCVIFYGFLSFIELFYYLRDPRKRKKIIYIIIYIFC\n" +
                        "FLILMYILLIMDSYFIVNIIEFYQKYENGFKFFDNINRVILMHLEKGFNF\n" +
                        "FKSLF\n" +
                        ">CAC24599.1    sequence:AJ294725:25425:28046:+  ORF519; homology to ORF516 of Euglena cpDNA;   complete gene\n" +
                        "MFSNYLLSFSYRLNWDFIKWNLVDNIISLFHHEIHILSKNLNFRSIKKKQ\n" +
                        "HLLFKSFYTRFVSVRDSVDNNFFFKSNIISSKEKFFIVFFLCYKRNFFYN\n" +
                        "LFFYNIEIINLSFKFNFFLFYKFCFNNLVKFVMYPFLELKTENFVFNFNF\n" +
                        "YTNLYDIFLNFKKILLKNFMKLYYFTINFNNKFNYMNKKWLYKNLTFNIN\n" +
                        "FLKYFLKLNNFIFNGSILFFIFNFMFNGLKSFIQRKCFMNNEFIYVSSLK\n" +
                        "NIYFFFKSYNEFNICINYLIYFLKYKGINFNFINDHVKNFLTNGLTFNFI\n" +
                        "KFFNFGYKFLFKLNEKDINYYKFNIKTLIKNFYIKNIFYTICLINNKIKN\n" +
                        "WLDKYFLFVNKKYLFLELDIFISKLLWIKIKKYHPKKSNIWIYSKYWKNF\n" +
                        "SGIWKFFIINNISGKMIFLKYHYDFNNYLLYLKSNYSGTFSYLYTFNLYN\n" +
                        "SNKKKNFLFEKFKYKFFPKFLDLYITQKGQCYICKKHIYSKKFKIIKLKF\n" +
                        "DNNKFSKNIYLLHFYCNFI\n" +
                        ">CAC24602.1    sequence:AJ294725:29718:30095:+  ORF125b;   complete gene\n" +
                        "MKKRRGPSEDENPRPEKLFTQKVFDYISRVILKYFKKTYKFIIYILKNLT\n" +
                        "LFKILYKCFPYIKNFILKIDKIFFHVLIKSINFIKYIPQLIHDKIFEFFW\n" +
                        "FILKIFQILIFVKIFKYVIKKFIIY\n" +
                        ">CAC24605.1    sequence:AJ294725:31811:32179:+  ORF122;   complete gene\n" +
                        "MMNINSSFNNDGTQDPKKDLILSNSNENEYDYIIKLIYENLYNICFSINF\n" +
                        "VLKKIYLDKFVYKYLPYIEIFLKMNKEKCCCRLKKFFEKDKIKLYKIYHK\n" +
                        "FKNFLTLNFSNSFTYMIKINIY\n" +
                        ">CAC24607.1    sequence:AJ294725:33196:33831:+  ORF211;   complete gene\n" +
                        "MFIYYINMKTEKTNYIEILIIKLIFFILTPIKIIFFIAKKIIKNPIIYRF\n" +
                        "IFKYLLYMQNKIIIINNKEYFYRIPKKKEYWEWFSAKPLYVNGKLINEIK\n" +
                        "TKEQRINFSLGKMIIKESESLTELEYVLLDLFWFGPFQMKYQNILRQNDI\n" +
                        "IIKKGVKNIKKIFQENNKFKGINLIFQKTDICKIYSGKFYTYERITEDNI\n" +
                        "LLIYVFIKNKD\n" +
                        ">CAC24612.1    sequence:AJ294725:39421:41097:-  ORF558;   complete gene\n" +
                        "MAKNRKLPNPEDLLFWIRYQMFFFWKKVKRIHIVRKFRKFIYNFFIFLDD\n" +
                        "LLLSSVRKVRKFSFFLIFKYKYFIINLEDFLKFIKEIFDTSVLIVSVGTR\n" +
                        "FFHESESQEKDSELIFNFIPEIINSDGLMGTKVLLESKKILYENENKEKD\n" +
                        "LKLIVHFIPDIINNNVLIGVKVLLEKKKIFYENENIKDLEFIEGSELEGQ\n" +
                        "EIKSEDIEEKVVDKDYDDSEGRVLLDESDSQAYFCREIRTREFWKQKYGN\n" +
                        "RFYYLNGHGIGGNICANDFVEFKDIKDIKKRKKYDSNKNDILVGVRDLLR\n" +
                        "EHLKEKKMNLKLSGDKRIEEYDPNFNFDNPDLISSFNSTSTSTSTSTSSS\n" +
                        "NDLNLDSDSDDSDSDDSDSDSDSDSDSEIDYLDFNFDDSQLDEEGREIKK\n" +
                        "KMMIKSLRLYRDFALQSMYGADFFMMETESDDDSDSDIDEFEKVKNKYKL\n" +
                        "TFDISKEIEKDNISDFDYFLLDLFLYGPLNFKVTDICDIDQMYRVQRRER\n" +
                        "YEKMFETYKHISSIFAFSINFIFIPSDRFISKDSLQGEFIFDEFHSMGNE\n" +
                        "LKVLILYW\n" +
                        ">CAC24615.1    sequence:AJ294725:62152:63432:+  ORF426;   complete gene\n" +
                        "MDLFLQIRKVNLFFPDKRDRPFSPDRINRPFSPDKKGEPIFPDKRDRPFS\n" +
                        "SDRINRPFSPDKKGEPIFPDKKDRPFSSDRINRPFSPDKKGEPIFPDKRD\n" +
                        "RPFSPDKKGEYIYPDKRDRSFSPYRINRSFYQDKKGESIYLDKRDKYFFS\n" +
                        "DRKNRHFFLDKKDEPIFTDDINKSIFLDEKDKLSYVDKKNISFSVGDGKS\n" +
                        "ESVYRDKMDKFIFSNESNKSFYLDKKDESFYLDMMNTPFYSDWRNRLFNP\n" +
                        "DKSNKSFSSNKKDESVFFDKRNKLFSADKGNIPFSLNEKSEPVYFDKKDK\n" +
                        "FIFSDKRDKPIFSDNKDKVFFSNKENKFIFSDEKYESIFKDRPFFIDRSK\n" +
                        "YNKPFFIDKSKYNRPFFIDKSKSNNIPFFSYQKKEPFIYRKNKPLNYQKN\n" +
                        "KNFFYKRKRKKKLNRLFCKMAMVYIL";

                $('#egQuery').click(function () {
                    $('#queryText').val(eg);
                    $("#form").formValidation("revalidateField", "queryText")
                });
            });

            function sort_nodes(asc) {
                tree.traverse_and_compute(function (n) {
                    var d = 1;
                    if (n.children && n.children.length) {
                        d += d3.max(n.children, function (d) {
                            return d["count_depth"];
                        });
                    }
                    n["count_depth"] = d;
                });
                tree.resort_children(function (a, b) {
                    return (a["count_depth"] - b["count_depth"]) * (asc ? 1 : -1);
                });
            }


            function mySearch() {
                var form = $("#form");
                form.formValidation("revalidateField", "queryText");
                form.formValidation("revalidateField", "file");

                var fv = form.data("formValidation");
                fv.validate();
                if (fv.isValid()) {
                    var form1 = new FormData($("#form")[0]);
                    var element = "<div><span id='info'>Running...</span>&nbsp;<img class='runningImage' src='/assets/images/running2.gif' style='width: 30px;height: 20px;'></div>"
                    var index = layer.alert(element, {
                        skin: 'layui-layer-lan'
                        , closeBtn: 0,
                        title: "Info",
                        btn: []
                    });
                    $.ajax({
                        url: "@routes.ToolsController.muscle()",
                        type: "post",
                        processData: false,
                        contentType: false,
                        data: form1,
                        async: false,
                        success: function (data) {
                            layer.close(index);
                            if (data.valid === "false") {
                                swal("Error", data.message, "error");
                                $("#result").hide()
                            } else {
                                $("#out").html(data.out);
                                if (data.tree === "") {
                                    $("#treeContent").hide()
                                } else {
                                    $("label").removeClass("active");
                                    $("#defaultAlign,#linear").addClass("active");
                                    $("#treeOut").html(data.tree);
                                    var example_tree = data.tree;
                                    tree = d3.layout.phylotree()
                                            .svg(d3.select("#tree_display")).radial(false);
                                    tree.spacing_x(75, true);
                                    tree.spacing_y(100, true);
                                    tree(example_tree)
                                            .layout();
                                    $("#treeContent").show()
                                }
                                $("#result").show()
                            }
                        }
                    });
                }
            }

            function formValidation() {
                $('#form').formValidation({
                            framework: 'bootstrap',
                            icon: {
                                valid: 'glyphicon glyphicon-ok',
                                invalid: 'glyphicon glyphicon-remove',
                                validating: 'glyphicon glyphicon-refresh'
                            },
                            fields: {
                                queryText: {
                                    validators: {
                                        notEmpty: {
                                            message: 'This is not be empty!'
                                        },
                                        regexp: {
                                            regexp: /^(>.*\n[a-zA-Z\n]+\s*){2,}$/,
                                            message: "Sequences is invalid(at least two sequences)!"
                                        }
                                    }
                                },
                                file: {
                                    validators: {
                                        notEmpty: {
                                            message: 'File is not be empty!'
                                        },
                                        file: {
                                            extension: 'fa,fasta',
                                            message: 'Sequences file must is a fa/fasta file！'
                                        }
                                    }
                                }
                            }
                        }
                );
            }

    </script>

}